package com.xuan.shop.config;

import com.xuan.shop.interceptor.AuthorityInterceptor;
import lombok.SneakyThrows;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * mvc相关配置
 */
@Configuration
public class MyConfig implements WebMvcConfigurer {


    @Bean
    public AuthorityInterceptor authorityInterceptor(){//在拦截器之前创建对象，防止为空
        return new AuthorityInterceptor();
    }
    /**
     *处理跨域问题
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowCredentials(true)
                .allowedOriginPatterns("*")
                .allowedMethods("Get","Post","Put","Delete")
                .maxAge(60*60);
    }

    @Override
    /**
     * 处理日期格式转换
     */
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new Converter<String,Date>() {
            @SneakyThrows
            @Override
            public Date convert(String s){
                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
                Date d=sdf.parse(s);
                return d;
            }
        });
    }

    /**
     * 拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authorityInterceptor())
                .addPathPatterns("/api/**")//添加拦截器的拦截的类型
                .excludePathPatterns("/api/user/login")//排除拦截登陆页面
                .excludePathPatterns("/api/car/findAll")
                .excludePathPatterns("/api/car/findByBand")
                .excludePathPatterns("/api/car/*")
                .excludePathPatterns("/api/user/addUser")
                .excludePathPatterns("ws://localhost:8090/websocket/registerUser");

    }
}
